Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

212
Visualizações
Javascript Agregar elemento a la matriz en un índice específico y removedor Separador "Unirse"

Sé que esta pregunta se ha hecho muchas veces, pero no puedo encontrar la solución a mi problema específico. Supongo que necesito refactorizar mi código por completo, pero me vendría bien alguna orientación.

Estoy practicando OOP en Javascript. Me gustaría unirme a una matriz y agregar una conjunción "y" antes del último elemento. De esa manera [1, 2, 3] ==> "1, 2 y 3".

He incluido mi código con los comentarios a continuación. Como verá, la salida actual que obtengo es "1, 2 y 3". ¿Cómo puedo deshacerme de la coma adicional? ¿Estoy haciendo esto de la manera incorrecta?

 class Person { constructor(first, last, age, gender, interests) { this.name = { first: first, last: last, }; this.age = age; this.gender = gender; this.interests = interests; } greeting() { console.log(`Hi! I'm ${this.name.first} ${this.name.last}.`) } bio() { // store the index of the last element of the array in a variable called index let index = this.interests.length - 1; // store the conjunction for end of array let conjunction = " and" // insert the conjunction before last element in array this.interests.splice(index, 0, conjunction) // join the array into a string separated by commas let interestsString = this.interests.join(", "); console.log(interestsString); } } let person1 = new Person('test', 'test', '29', 'Male', ['skiing', 'cooking', 'gardening']); console.log(person1.bio());

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Use Intl.ListFormat() para convertir la lista en una cadena mientras maneja el separador y la conjunción:

 const listFormatter = new Intl.ListFormat('en', { style: 'long', type: 'conjunction' }); class Person { constructor(first, last, age, gender, interests) { this.name = { first: first, last: last, }; this.age = age; this.gender = gender; this.interests = interests; } greeting() { console.log(`Hi! I'm ${this.name.first} ${this.name.last}.`) } bio() { return listFormatter.format(this.interests); } } let person1 = new Person('test', 'test', '29', 'Male', ['skiing', 'cooking', 'gardening']); console.log(person1.bio());

Otra opción es usar la manipulación de matrices: si la matriz contiene solo un elemento, devolver ese elemento. Si contiene más de un elemento, cree una nueva matriz con todos los elementos originales, excepto el último, y el último elemento después de agregarle "y". Únete a la matriz.

 class Person { constructor(first, last, age, gender, interests) { this.name = { first: first, last: last, }; this.age = age; this.gender = gender; this.interests = interests; } greeting() { console.log(`Hi! I'm ${this.name.first} ${this.name.last}.`) } bio() { return this.interests.length > 1 // if there are multiple items ? [ ...this.interests.slice(0, -1), // get all items but the last `and ${this.interests.at(-1)}` // add the last item with "and" ].join(', ') // join : this.interests.at(0); // just take the single existing item } } let person1 = new Person('test', 'test', '29', 'Male', ['skiing', 'cooking', 'gardening']); console.log(person1.bio());

about 4 years ago · Juan Pablo Isaza Relatório

0

Aquí hay una forma de hacer lo que necesita.

 class Person { constructor(first, last, age, gender, interests) { this.name = { first: first, last: last, }; this.age = age; this.gender = gender; this.interests = interests; } greeting() { console.log(`Hi! I'm ${this.name.first} ${this.name.last}.`) } bio() { let interestsString = this.interests.join(', ').replace(/, ([^,]*)$/, ' and $1') console.log(interestsString); } } let person1 = new Person('test', 'test', '29', 'Male', ['skiing', 'cooking', 'gardening']); console.log(person1.bio());

about 4 years ago · Juan Pablo Isaza Relatório

0

cuando usaste un empalme como este

 this.interests.splice(index, 0, conjunction)

agrega el elemento a la matriz, luego la función de combinación agregó otro "," mejor simplemente cambiar el elemento en sí mismo y agregarle y.

como esto:

 let changeTo = conjunction + this.interests[index]; this.interests.splice(index, 1, changeTo);
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda